import * as React from 'react'
import Card from 'antd/lib/card'
import List from './components/list'
import TodoInput from './components/todo-input'
import { ToShowInterface } from './components/list-item'
import './App.css'

interface AppStates {
  value: string
  todos: Array<ToShowInterface>
}

export default class App extends React.Component<{}, AppStates> {
  constructor(p: {}) {
    super(p)
    this.state = {
      value: '',
      todos: [{ text: 'test', isComplete: false, isEditing: false }],
    }
  }
  // 输入框发生改变
  onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value.trim()
    this.setState({
      value,
    })
  }
  // 添加
  handleAdd = () => {
    if (!this.state.value) {
      return
    }
    this.setState({
      todos: [...this.state.todos, { text: this.state.value, isComplete: false, isEditing: false }],
      value: '',
    })
  }
  // 删除
  handleDel = (index: number) => {
    let { todos } = this.state
    todos.splice(index, 1)
    this.setState({
      todos: [...todos],
    })
  }
  // 点击变成编辑状态
  switchListItemEditStatus = (index: number, status: boolean) => {
    let { todos } = this.state
    todos[index].isEditing = status
    this.setState({ todos })
  }
  // 编辑状态下点击保存按钮
  onClickSaveButton = (index: number, value: string) => {
    let { todos } = this.state
    todos[index].text = value
    todos[index].isEditing = false
    this.setState({ todos })
  }
  // 切换完成状态
  switchListItemCompleteStatus = (index: number, e: React.ChangeEvent<HTMLInputElement>) => {
    let { todos } = this.state
    todos[index].isComplete = e.target.checked
    this.setState({ todos })
  }
  render() {
    return (
      <div>
        <Card>Welcome to React</Card>
        <Card>
          <TodoInput value={this.state.value} handleAdd={this.handleAdd} onInputChange={this.onInputChange} />
        </Card>
        <Card>
          <List
            todos={this.state.todos}
            onClickDelButton={this.handleDel}
            switchListItemEditStatus={this.switchListItemEditStatus}
            onClickSaveButton={this.onClickSaveButton}
            switchListItemCompleteStatus={this.switchListItemCompleteStatus}
          />
        </Card>
      </div>
    )
  }
}
